import { _decorator, Component, instantiate, Node, Prefab, ScrollView } from 'cc';
import { UIManager } from '../common/UIManager';
import RankApi from '../api/RankApi';
import { RankOper } from '../entity/Rank';
import { AllyListItem } from './AllyListItem';
import { Ally, AllyOperateType } from '../entity/Ally';
import { EventManager } from '../event/EventManager';
import AllyApi from '../api/AllyApi';
const { ccclass, property } = _decorator;

@ccclass('AllyList')
export class AllyList extends Component {
    
    @property(ScrollView)
    scrollView:ScrollView
    @property(Node)
    content:Node
    @property(Node)
    empty:Node
    @property(Prefab)
    allyPrefab:Prefab

    private page:number = 0
    private total:number = 0
    private size:number = 20
    start() {

        this.scrollView.node.on('scroll-to-top', () => {
            console.log('scroll-to-top....')
        }, this);
        this.scrollView.node.on('scroll-to-bottom', this.scrollToBottom, this);

        this.query()
        this.getList(1)
    }

    async getList(page){
        this.page = page

        let params = {
            oper: RankOper.Union,
            page: page
        }
        await UIManager.instance.showLoading()
        let res = await RankApi.Execute(params)
        UIManager.instance.closeLoading()
        console.log(res)
        let list = res.data.list
        this.total = res.data.total
        for (let i = 0; i< list.length; i++) {

            let node = instantiate(this.allyPrefab)
            this.content.addChild(node)

            let ally = Ally.createByObj(list[i])
            node.getComponent(AllyListItem).setData(ally)
        }

        if(list.length > 0){
            this.empty.active = false
        }
    }

    scrollToBottom(){
        if(this.page* this.size >= this.total){
            UIManager.instance.tip('没有更多了')
            return
        }

        this.page ++
        this.getList(this.page)
    }

    async query(){
        await UIManager.instance.showLoading()
        let res = await AllyApi.Execute({
            op:AllyOperateType.Query
        })
        UIManager.instance.closeLoading()
        console.log(res)

        EventManager.instance.emit(EventManager.EventType.AllyRedDot, res.data)
    }
    
}


